<template>
     <page-container title="部门列表">
        <template #extra>
           
            <el-button 
                style="float: right;margin-right: 20px;"
                type="primary" 
                @click="addDepartments"
            >添加部门</el-button>
            <el-button 
                style="margin-right: 20px;"
                type="danger" 
                @click="handleBatchDelete"
            >批量删除</el-button>
    </template>
        <el-table 
            :data="departments" 
            style="width: 100%" 
            v-loading="tableLoading"
            @selection-change="handleSelectionChange"
        > 
            <el-table-column type="selection"  width="55" />
            <el-table-column type="index" label="序号" width="100"/>
            <el-table-column prop="departmentName" label="部门名称" >
                <template #default="scope">
                    <el-popover effect="light" width="auto" trigger="contextmenu">
                        <template #reference>
                            <el-tag>{{ scope.row.departmentName }}</el-tag>
                        </template>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间">
                <template #default="{ row }">
                    {{ formatDateTime(row.createTime) }}
                </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间">
                <template #default="{ row }">
                    {{ formatDateTime(row.updateTime) }}
                </template>
            </el-table-column>
            
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <el-button 
                        type="primary" 
                        :icon="Edit" 
                        circle 
                        plain 
                        @click="editDepartment(scope.row)"
                    />
                    <el-button 
                        type="danger" 
                        :icon="Delete" 
                        circle 
                        plain 
                        @click="deleteDepartments(scope.row)"
                    />
                </template>
            </el-table-column>

            <template #empty>
                <el-empty description="暂无数据" />
            </template>
      
           
        </el-table>
        <el-drawer 
            v-model="dialogVisible" 
            title="部门信息" 
            width="50%" 
            direction="rtl"
        >
        <div>
      <el-button @click="innerDrawer = true" type="primary" style="margin-left: 40px;margin-bottom: 20px;" v-show="isBatchAdd">批量添加</el-button>
      <el-drawer
        v-model="innerDrawer"
        title="批量添加部门"
        :append-to-body="true"
        :before-close="handleClose"
      >
        <div class="batch-add-form">
            <div v-for="(item, index) in BatchAddform" :key="index" class="form-item">
                <el-form-item label="部门名称" required>
                    <el-input 
                        v-model="item.departmentName"
                        placeholder="请输入部门名称"
                    >
                        <template #append>
                            <el-button 
                                type="danger" 
                                icon="Delete"
                                @click="BatchAddform.splice(index, 1)"
                                :disabled="BatchAddform.length === 1"
                            />
                        </template>
                    </el-input>
                </el-form-item>
            </div>
            
            <div class="form-actions">
                <el-button type="primary" @click="newAddRow">新增一行</el-button>
                <el-button type="success" @click="saveBatchDepartments">保存</el-button>
            </div>
        </div>
      </el-drawer>
    </div>
            <el-form 
                :model="form" 
                label-width="120px" 
                ref="formRef"
            >
                <el-form-item label="部门名称" required>
                    <el-input 
                        v-model="form.departmentName"
                        placeholder="请输入部门名称"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="saveDepartment">保存</el-button>
                    <el-button @click="dialogVisible = false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
    </page-container>
</template>

<script setup>
import { getDepartments, addDepartment, updateDepartment, deleteDepartment, deleteBatchDepartments, batchAddDepartments } from '@/api/department'
import { ref, onMounted } from 'vue'
import { Edit, Delete } from '@element-plus/icons-vue'
import PageContainer from '@/components/PageContainer.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const departments = ref([])
const tableLoading = ref(true)
const dialogVisible = ref(false)
const innerDrawer = ref(false)
const isBatchAdd = ref(false)
const form = ref({})
const BatchAddform = ref([
    { departmentName: '' }
])
const selectedDepartments = ref([])
const loadDepartments = async () => {
    tableLoading.value = true
    try {
        const res = await getDepartments()
        departments.value = res.data
    } catch (error) {
        ElMessage.error('获取部门列表失败', error)
    } finally {
        tableLoading.value = false
    }
}
const newAddRow = () => {
    BatchAddform.value.push({ departmentName: '' })
}
const addDepartments = () => {
    dialogVisible.value = true
    isBatchAdd.value = true
    form.value = {}
}
const editDepartment = (row) => {
    dialogVisible.value = true
    isBatchAdd.value = false
    form.value = { ...row }
}

const saveDepartment = async () => {
    try {
        if (form.value.departmentId) {
            await updateDepartment(form.value)
            ElMessage.success('修改部门成功')
        } else {
            await addDepartment(form.value)
            ElMessage.success('添加部门成功')
        }
        loadDepartments()
        dialogVisible.value = false
    } catch (error) {
        ElMessage.error('添加部门失败', error)
    }
}

const deleteDepartments = async (row) => {
    try {
        ElMessageBox.confirm('确定要删除该部门吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }).then(async () => {
            await deleteDepartment(row.departmentId)
            ElMessage.success('删除部门成功')
            loadDepartments()
        }).catch(() => {
            ElMessage.info('已取消删除')
        })
    } catch (error) {
        ElMessage.error('删除部门失败', error)
    }
}

const handleSelectionChange = (selection) => {
    selectedDepartments.value = selection.map(item => item.departmentId)
}

const handleBatchDelete = async () => {
    try {
        if (selectedDepartments.value.length === 0) {
            ElMessage.warning('请先选择要删除的部门')
            return
        }
        ElMessageBox.confirm('确定要删除这些部门吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }).then(async () => {
            await deleteBatchDepartments(selectedDepartments.value)
            ElMessage.success('批量删除部门成功')
            loadDepartments()
        }).catch(() => {
            ElMessage.info('已取消删除')
        })
    } catch (error) {
        ElMessage.error('批量删除部门失败', error)
    }
}
const handleBatchAdd = () => {
    innerDrawer.value = true
    BatchAddform.value = [{ departmentName: '' }]
}
const saveBatchDepartments = async () => {
    try {
        const departments = BatchAddform.value
            .filter(item => item.departmentName.trim() !== '')
            .map(item => ({
                departmentName: item.departmentName.trim()
            }))

        if (departments.length === 0) {
            ElMessage.warning('请至少输入一个部门名称')
            return
        }

        const res = await batchAddDepartments(departments)
        if (res.code === 200) {
            ElMessage.success('批量添加成功')
            innerDrawer.value = false
            loadDepartments()
        } else {
            ElMessage.error(res.message || '批量添加失败')
        }
    } catch (error) {
        console.error('批量添加失败：', error)
        ElMessage.error('批量添加失败：' + error.message)
    }
}
const handleClose = (done) => {
    ElMessageBox.confirm('确认关闭？未保存的数据将丢失')
        .then(() => {
            BatchAddform.value = [{ departmentName: '' }]
            done()
        })
        .catch(() => {})
}
const formatDateTime = (dateStr) => {
    if (!dateStr) return '--'
    const date = new Date(dateStr)
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    })
}
onMounted(() => {
    setTimeout(() => {
        loadDepartments()
    }, 1000)
})
</script>

<style scoped>
.batch-add-form {
    padding: 20px;
}
.form-item {
    margin-bottom: 15px;
}
.form-actions {
    margin-top: 20px;
    display: flex;
    gap: 10px;
}
</style>


